<?php
namespace app\manager\controller;

use think\Db;
use think\Controller;
use think\facade\Session;

class Account extends Controller
{
    public function login()
    {
        if(request()->isAjax())
        {
            $data['name'] = input('post.name');
            $password = input('post.password');
            $admin_info = Db::name('admin')->where($data)->find();
            if($admin_info)
            {
                if(password_verify($password, $admin_info['password']))
                {
                    Session::set('admin_info', $admin_info);
                    return responseJson(200, '登录成功');
                }else{
                    return responseJson(400, '账号或者密码错误');
                }
            }else{
                return responseJson(400, '账号不存在');
            }
        }else{
            return $this->fetch('login');
        }
    }

    public function reg()
    {
        $data['name'] = 'big';
        $data['password'] = password_hash('123123', PASSWORD_DEFAULT);
        Db::name('admin')->insert($data);
    }

    /*
     * 管理员
     */
    public function admin_info()
    {
        $admin_info = Session::get('admin_info');
        if(!$admin_info)
        {
            return $this->fetch('login');
        }
        if(request()->isAjax())
        {
            $data['name'] = input('name');
            if(input('password'))
            {
                $data['password'] = password_hash(input('password'), PASSWORD_DEFAULT);;
            }
            $result = Db::name('admin')->where('id', $admin_info['id'])->update($data);
            if(!$result)
            {
                return responseJson(400, '修改失败');
            }
            return responseJson(200, '修改成功');
        }else{
            return $this->fetch('admin_info');
        }
    }

    public function logout()
    {
        Session::delete('admin_info');
        return $this->fetch('login');
    }
}